<?
class cacher extends errorHandler{
	public $timeout=300;
	public $serialise=true;
	public $directory=NULL;
	public $ageOfData=NULL;
	public function __construct(){
		parent::__construct();
		$this->directory=CACHE_DIR;
	}
	public function save($key,$data,$timeout=NULL,$serialise=NULL){
		$result=false;
		
		$this->timeout=($timeout===NULL)?$this->timeout:$timeout;
		$this->serialise=($serialise===NULL)?$this->serialise:$serialise;
		
		if($this->timeout>0){
			$cached_file=$this->directory.@md5($key).".cached";
	
			if($this->serialise){
				$data=serialize($data);
			}
	
			if(@file_put_contents($cached_file,$data)){
				$result=true;
			}else{
				$this->addError($this->ERROR_CACHE_SAVE,"cacher.load.errorSavingCacheData",array("timeout"=>$this->timeout,"serialise"=>$this->serialise,"cached_file"=>$cached_file,"data"=>$data));
			}
		}else{
			$result=true;
		}
		return($result);
	}
	public function load($key,$timeout=NULL,$serialise=NULL){
		$result=false;
		
		$this->timeout=($timeout===NULL)?$this->timeout:$timeout;
		$this->serialise=($serialise===NULL)?$this->serialise:$serialise;
		
		if($this->timeout>0){
			$cached_file=$this->directory.@md5($key).".cached";
			
			if(@file_exists($cached_file)){
				$last_modified=@filemtime($cached_file);
				
				if($last_modified>time()-$this->timeout){
					$this->ageOfData=time()-$last_modified;
					$result=@file_get_contents($cached_file);
					if($result){
						if($this->serialise){
							$result=unserialize($result);
						}
					}else{
						$this->addError($this->ERROR_CACHE_READ,"cacher.load.errorReadingCachedFile",array("timeout"=>$this->timeout,"serialise"=>$this->serialise,"cached_file"=>$cached_file));
					}
				}
			}
		}
		return($result);
	}
};
?>